package com.superbit.web.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superbit.core.constant.UserStatusConstant;
import com.superbit.core.exception.BusinessException;
import com.superbit.core.exception.ParamInvalidException;
import com.superbit.core.service.RegisterService;
import com.superbit.utils.mailutil.EmailFailException;
import com.superbit.web.listener.ServiceBeanFactory;
import com.superbit.web.utils.CommonUtil;
import com.superbit.web.utils.JsonResponseUtil;
import com.superbit.web.utils.PictureCheckCode;
import com.superbit.web.utils.StringValidateUtil;

/** @author  WangZhenwei 
  * @date 创建时间：2018年1月22日 下午5:59:07  
  * @descrip  用户注册模块的controller层
  */
@Controller
@RequestMapping("/userRegist.act")
public class UserRegisterController {

	private static Logger log = LoggerFactory.getLogger(TradeLogController.class);
	
	private RegisterService registerService; //不需要加Autowired注解
	
	/**
	 * @function 构造器注入service对象
	 */
	@PostConstruct
	private void init(){
		registerService = ServiceBeanFactory.getBean(RegisterService.class);
	}
	
	/**
	 * @function 生成图片验证码
	 * @param session
	 * @return
	 */
	@RequestMapping(params = "cmd=createValidateCode")
	public void createCheckCode(HttpSession session, HttpServletResponse resp) {
		log.info("cmd=createValidateCode");
		PictureCheckCode vCode = new PictureCheckCode(); 
    	vCode.createCode();
    	BufferedImage buffImg = vCode.getBuffImg();
		String code = vCode.getCode();
    	//将生成的验证码存在session中
		session.setAttribute("checkcode", code);
	    //设置响应头通知浏览器以图片的形式打开
		resp.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
	    //设置响应头控制浏览器不要缓存
		resp.setDateHeader("expries", -1);
		resp.setHeader("Cache-Control", "no-cache");
		resp.setHeader("Pragma", "no-cache");
	    //将图片写给浏览器
	    try {
			ImageIO.write(buffImg, "png", resp.getOutputStream());
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	
	/**
	 * @function 手机注册
	 * @param req
	 * @param areaCode		区号
	 * @param phone			手机号
	 * @param consumerCode	图片验证码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=phoneRegister")
	public String phoneRegister(HttpServletRequest req, String areaCode, 
			final String phone, final String consumerCode) {
		log.info("phoneRegister");
		
		//Map<String,Object> codeMap = new HashMap<String,Object>();
		//JSONObject obj = new JSONObject();
		String result = "";
		// 1.根据IP确定国家，如果是中国确定，+86显示
		
		// 2.手机校验(为不为空串；是不是手机号；该手机号是否注册过)
		StringValidateUtil.validateNotEmpty(areaCode, "areaCode");
		CommonUtil.areaCodeCheck(areaCode);
		StringValidateUtil.validateNotEmpty(phone, "phone");
		 
		boolean isPhone = StringValidateUtil.isPhone(areaCode + phone);
		if(!isPhone){
			return JsonResponseUtil.buildNormalExcepResonpe("US651", "The mobile is not mobile").toString();
		}
		// 3.图形验证码 是否正确
		String pictureCaptcha = (String)req.getSession().getAttribute("checkcode");
		if(StringUtils.isEmpty(pictureCaptcha) || !pictureCaptcha.equalsIgnoreCase(consumerCode)){
			// 从session中去除验证码
			req.getSession().removeAttribute("checkcode");
			return JsonResponseUtil.buildNormalExcepResonpe("US601", "Image verification code does not match!").toString();
		}
		
		
		try {
			registerService.phoneRegister(areaCode, phone);
			result = JsonResponseUtil.buildSucessResonpe(true).toString();
		} catch (BusinessException e) {	
			result = JsonResponseUtil.buildBusiExcepResonpe(e).toString();
			log.error("phoneRegister", result);
		}	
		
		req.getSession().removeAttribute("checkcode");
		return result;
	}

	/**
	 * 手机注册激活
	 * @param mobile    手机号
	 * @param captcha   验证码
	 * @param password  密码
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=activePhone")
	public String activePhone(HttpServletRequest req,String phone, final String activeCode, final String password, final String repassword, final String userProtocol){
		log.info("activePhone");

		String result = "";
		StringValidateUtil.validateNotEmpty(phone, "phone");
		StringValidateUtil.validateLength(32, password, "password");
		// 手机号格式是否正确
		boolean isMobile = StringValidateUtil.isPhone(phone);
		if(!isMobile){			
			throw new ParamInvalidException("mobile", " not mobile");
		}
		
		
		if(!StringValidateUtil.isLoginPassword(password)){					
			req.getSession().removeAttribute("password");
			log.error("activePhone", JsonResponseUtil.buildNormalExcepResonpe("US616", "validate password").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US616", "validate password").toString();
		}
				
		StringValidateUtil.validateNotEmpty(repassword, "repassword");
		if(!password.equals(repassword)){					
			req.getSession().removeAttribute("repassword");
			log.error("activePhone", JsonResponseUtil.buildNormalExcepResonpe("US617", "different password").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US617", "different password").toString();
		}
				
		if(!UserStatusConstant.USER_PROTOCOL_SELECT.equals(Integer.parseInt(userProtocol))){					
			req.getSession().getAttribute("userProtocol"); 
			log.error("activePhone", JsonResponseUtil.buildNormalExcepResonpe("US618", "please read the user protocol").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US618", "please read the user protocol").toString();
		}
		
		StringValidateUtil.validateNotEmpty(activeCode, "captcha");
		StringValidateUtil.validateNotEmpty(password, "password");
		try {					
			registerService.activePhone(phone, activeCode, password);							
			result = JsonResponseUtil.buildSucessResonpe(true).toString();
		} catch (BusinessException e) {			
			result = JsonResponseUtil.buildBusiExcepResonpe(e).toString();
			log.error("activePhone", result);
		}
		return result;		
	}
	
	/**
	 * @function 邮箱注册
	 * @param req
	 * @param email			邮箱
	 * @param consumerCode	图片验证码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=emailRegister")
	public String emailRegister(HttpServletRequest req, String email, 
			final String consumerCode) {
		log.info("cmd=emailRegister");
		//Map<String, Object> codeMap = new HashMap<String,Object>();
		//JSONObject obj = new JSONObject();
		String result = "";
		// 1.根据IP确定国家，如果是中国确定，+86显示
		
		// 2.邮箱校验(为不为空串；是不是邮箱；该邮箱是否注册过)
		StringValidateUtil.validateNotEmpty(email, "email");
		boolean isEmail = StringValidateUtil.isEmail(email);
		if(!isEmail){
			throw new ParamInvalidException("email", "not email ");
		}
		// 3.图形验证码 是否正确
		String pictureCaptcha = (String) req.getSession().getAttribute("checkcode");
		if(StringUtils.isEmpty(pictureCaptcha) || !pictureCaptcha.equalsIgnoreCase(consumerCode)){
			
			req.getSession().removeAttribute("checkcode");
			log.error("emailRegister", JsonResponseUtil.buildNormalExcepResonpe("US601", "Image verification code does not match!").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US601", "Image verification code does not match!").toString();
		}
		
		try {
			registerService.emailRegister(email);
			result = JsonResponseUtil.buildSucessResonpe(true).toString();
		}catch (BusinessException e) {
			result = JsonResponseUtil.buildBusiExcepResonpe(e).toString();
			log.error("emailRegister", result);
		}catch (EmailFailException e) {
			result = JsonResponseUtil.buildNormalExcepResonpe("US626", " Email Send Fail!").toString();
			log.error("emailRegister", result);
		}		
		return result;
	}
	
	/**
	 * 邮箱注册激活
	 * @param email        邮箱号
	 * @param activeCode   激活码
	 * @param password     密码
	 */
	@ResponseBody
	@RequestMapping(params = "cmd=activeEmail")
	public String activeEmail(HttpServletRequest req,String email, final String activeCode, final String password, final String repassword, final String userProtocol){
		log.info("cmd=activeEmail");

		String result = "";
		StringValidateUtil.validateNotEmpty(email, "email");
		StringValidateUtil.validateLength(32, password, "password");
		// 邮箱格式是否正确
		boolean isEmail = StringValidateUtil.isEmail(email);
		if(!isEmail){			
			throw new ParamInvalidException("email", " not email");
		}
		
		if(!StringValidateUtil.isLoginPassword(password)){					
			req.getSession().removeAttribute("password");
			log.error("activeEmail", JsonResponseUtil.buildNormalExcepResonpe("US616", "validate password").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US616", "validate password").toString();
		}
				
		StringValidateUtil.validateNotEmpty(repassword, "repassword");
		if(!password.equals(repassword)){					
			req.getSession().removeAttribute("repassword");
			log.error("activeEmail", JsonResponseUtil.buildNormalExcepResonpe("US617", "different password").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US617", "different password").toString();
		}
				
		if(!UserStatusConstant.USER_PROTOCOL_SELECT.equals(Integer.parseInt(userProtocol))){
			log.error("activeEmail", JsonResponseUtil.buildNormalExcepResonpe("US618", "please read the user protocol").toString());
			return JsonResponseUtil.buildNormalExcepResonpe("US618", "please read the user protocol").toString();
		}
		StringValidateUtil.validateNotEmpty(activeCode, "captcha");
		StringValidateUtil.validateNotEmpty(password, "password");
		try {					
			registerService.activeEmail(email, activeCode, password);							
			result = JsonResponseUtil.buildSucessResonpe(true).toString();
		} catch (BusinessException e) {
			result = JsonResponseUtil.buildBusiExcepResonpe(e).toString();
			log.error("activeEmail", result);
		}
		return result;		
	}
	
}
